import { defineStore } from "pinia";
import { getRandomImage, phoneLogin, phoneSms, pwdLogin } from "@/services/loginApi.ts";
import type { LoginPhoneSubmitType, LoginSubmitType, RandomImage } from "@/types/loginType.ts";

import { SMSMODE } from "@/types/SMSMODE.ts";

type State = {
    code: RandomImage
    isAccountOrPhone: boolean
    countDown: number,
    isCode: boolean
}

const useLoginStroe = defineStore('login', {
    state: (): State => ({
        code: {
            image: '',
            key: ''
        },
        isAccountOrPhone: true,
        countDown: 60,
        isCode: false
    }),
    getters: {

    },
    actions: {
        getCode(): RandomImage {
            return this.code
        },
        setCode() {
            const key = Date.now()
            getRandomImage({key}).then((res) => {
                if (res.code === 200) {
                    this.code = res.data
                }
            })
        },
        submit(data: LoginSubmitType) {
            return pwdLogin(data).then((res) => {
                if (res.code === 500 || res.code === 412) {
                    this.setCode()
                }
                if (res.code === 200) {
                    return res.data
                }
                return Promise.reject(res)
            })
        },

        phoneGetCode(phone: string) {
            phoneSms({
                phone,
                smsMode: SMSMODE.phone
            }).then((res) => {
                if (res.code === 200) {
                    this.countDown = 60
                    this.setIsCode(true)
                    this.setCountDown()
                }
            })
        },
        phoneSubmit(data: LoginPhoneSubmitType) {
            phoneLogin(data).then(() => {
            })
        },
        setIsAccountOrPhone(bool: boolean) {
            this.isAccountOrPhone = bool
        },
        getIsAccountOrPhone(): boolean {
            return this.isAccountOrPhone
        },
        setCountDown() {
            // this.countDown
            const count = setInterval(() => {
                if (this.countDown <= 0) {
                    clearInterval(count)
                    this.setIsCode(false)
                } else {
                    this.countDown--
                }
            }, 1000)
        },
        getCountDown() {
            return this.countDown
        },
        getIsCode() {
            return this.isCode
        },
        setIsCode(bool: boolean) {
            this.isCode = bool
        }
    },
})

export default useLoginStroe